package com.bcx.wind.workflow.imp.cmd.runtimecmd;

import com.bcx.wind.workflow.entity.WindOrder;
import com.bcx.wind.workflow.errorcontext.WindError;
import com.bcx.wind.workflow.interceptor.Command;
import com.bcx.wind.workflow.interceptor.CommandContext;
import com.bcx.wind.workflow.support.JsonHelper;

import java.util.Map;

import static com.bcx.wind.workflow.message.ErrorCode.DATABASE_OPERATE_ERROR;
import static com.bcx.wind.workflow.message.ErrorCode.OPERATE_FAIL;
import static com.bcx.wind.workflow.message.ErrorCode.QUERY_EMPTY;

/**
 *添加流程实例变量命令
 *
 * @author zhanglei
 */
public class AddOrderVariableCommand implements Command<Void> {

    /**
     * 流程实例号
     */
    private String orderId;

    /**
     * 变量集合
     */
    private Map<String,Object>  variable;

    /**
     * 需要更新的流程实例
     */
    private WindOrder windOrder;

    public AddOrderVariableCommand(String orderId,Map<String,Object> variable){
        this.orderId = orderId;
        this.variable = variable;
    }

    @Override
    public Void executor(CommandContext context) {
        if(this.variable == null){
            return null;
        }
        //校验
        checkArgs(context);
        //添加
        addVariable();
        //更新流程实例
        if(context.access().updateOrderInstance(this.windOrder) != 1){
            WindError.error(DATABASE_OPERATE_ERROR,null);
        }
        return null;
    }


    private void addVariable(){
        Map<String,Object> variable =  this.windOrder.variable();
        variable.putAll(this.variable);
        this.windOrder.setVariable(JsonHelper.toJson(variable));
    }


    private void checkArgs(CommandContext context){
        if(this.orderId == null){
            WindError.error(OPERATE_FAIL,null,"order","addVariable","orderId");
        }
        this.windOrder = context.access().getOrderInstanceById(this.orderId);
        if(this.windOrder == null){
            WindError.error(QUERY_EMPTY,null,"order",this.orderId);
        }
    }

}
